package com.dm.library.utils;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.dm.library.bean.ContractListBean;
import com.dm.library.bean.MessageBean;
import com.dm.library.bean.PhoneRecordBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: zhoulai
 * 修改时间: 2017/6/28 10:00
 */
public class PhoneDataUtils {

    private static Uri SMS_INBOX = Uri.parse("content://sms/");
    private static final long TIME = 30 * 24 * 60 * 60 * 1000;
    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds
            .Phone.NUMBER, ContactsContract.Contacts.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};


    public static int getSmsCount(Context context) {
        int size = 0;
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(SMS_INBOX, null, null, null, null);
        if (null == cursor) {
            return size;
        }
        try {
            while (cursor.moveToNext()) {
                if (size < Integer.MAX_VALUE) {
                    size++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }
        DMLog.d("手机短信总数量：" + size);
        return size;
    }


    public static ArrayList<MessageBean> getSmsRecordList(Context context, String keyWords) {
        if (keyWords != null && keyWords.length() > 0) {
            keyWords = keyWords + ",测试CS";
        }

        StringBuffer sbWhere = new StringBuffer();
        String where = "";
        if (StringUtils.isEmptyOrNull(keyWords)) {
            keyWords = "";
        }
        String[] array = keyWords.split(",");
        String[] selectionArgs;
        if (array != null && array.length > 0) {
            selectionArgs = new String[array.length + 1];
            for (int i = 0; i < array.length; i++) {
                if (i == array.length - 1) {
                    sbWhere.append(" body like ? ");
                } else {
                    sbWhere.append(" body like ? or ");
                }
                selectionArgs[i] = "%" + array[i] + "%";
            }
            sbWhere.append(" and date > ?");
            selectionArgs[array.length] = String.valueOf(System.currentTimeMillis() - TIME);
            selectionArgs[array.length] = "0";
        } else {
            selectionArgs = new String[1];
            selectionArgs[0] = String.valueOf(System.currentTimeMillis() - TIME);
            selectionArgs[0] = "0";
            sbWhere.append(" date > ?");
        }
        DMLog.d("短信过滤关键字：" + keyWords.trim());
        DMLog.d("where：" + sbWhere.toString());
        ArrayList<MessageBean> list = new ArrayList<>();
        ContentResolver cr = context.getContentResolver();
        String[] projection = new String[]{"_id", "address", "person", "date", "type", "body"};//"_id", "address", "person",, "date", "type
//        String where = " date >  " + (System.currentTimeMillis() - TIME) + " and body like \"%" + keyWords.trim() + "%\"";
        //SELECT _id, address, person, date, type, body FROM sms_secret WHERE ( date >  1499846245627 and  (  body like "%中国移动%"  or body like "%中国移动%"  ) ) ORDER BY date desc
//        Cursor cursor = cr.query(SMS_INBOX, projection, sbWhere.toString(), selectionArgs, "date desc");
        Cursor cursor = cr.query(SMS_INBOX, projection, sbWhere.toString(), selectionArgs, null);
        if (null == cursor)
            return list;
        try {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex("_id"));
                String address = cursor.getString(cursor.getColumnIndex("address"));    //手机号
                String person = cursor.getString(cursor.getColumnIndex("person"));      //联系人姓名
                String date = cursor.getString(cursor.getColumnIndex("date"));          //发送时间
                String type = cursor.getString(cursor.getColumnIndex("type"));          //类型
                String body = cursor.getString(cursor.getColumnIndex("body"));          //内容
                MessageBean messageBean = new MessageBean();
//                String t = TimeUtils.getTime(Long.parseLong(date));

                DMLog.i("ColumnIndex=======" + cursor.getColumnIndex("person"));
                DMLog.i("person============" + person);

                messageBean.setId(id);
                messageBean.setAddress(person);
                messageBean.setDespatcher(address);
                messageBean.setSendTime(date);
                messageBean.setType(type);
                messageBean.setContent(body);
                list.add(messageBean);
                //这里我是要获取自己短信服务号码中的验证码~~
//                Pattern pattern = Pattern.compile(" [a-zA-Z0-9]{10}");
//                Matcher matcher = pattern.matcher(body);
//                if (matcher.find()) {
//                    String res = matcher.group().substring(1, 11);
//                    mobileText.setText(res);
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }
        return list;
    }


    /**
     * 加载手机联系人
     */
    public static List<ContractListBean> getContactsList(Context context) {
        List<ContractListBean> mSortList = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);

        String phoneNumber;
        String phoneName;
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX).replace(" ", "");
                phoneNumber = phoneNumber.replace("-", "");
                if (null == phoneNumber || "".equals(phoneNumber)) {
                    continue;
                }
                phoneName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                ContractListBean sort = new ContractListBean();
                sort.setPhone(phoneNumber);
                sort.setName(phoneName);
                mSortList.add(sort);
            }
            phoneCursor.close();
        }
        return mSortList;
    }


    public static List<PhoneRecordBean> getCallHistoryList(Context context) {
        List<PhoneRecordBean> list = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = null;
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                return list;
            }
            /*
             * uri 需要查询的URI，（这个URI是ContentProvider提供的）
             * projection 需要查询的字段
             * selection sql语句where之后的语句
             * selectionArgs ?占位符代表的数据
             * sortOrder 排序方式
             */
//            String where = " date >  "+ (System.currentTimeMillis() - TIME);
            cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
                    new String[]{
                            CallLog.Calls.CACHED_NAME// 通话记录的联系人
                            , CallLog.Calls.NUMBER// 通话记录的电话号码
                            ,
                            CallLog.Calls.DATE// 通话记录的日期
                            , CallLog.Calls.DURATION// 通话时长
                            , CallLog.Calls.TYPE}// 通话类型
                    , null, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示

//                    cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
//                            new String[]{CallLog.Calls.CACHED_NAME// 通话记录的联系人
//                                    , CallLog.Calls.NUMBER// 通话记录的电话号码
//                                    , CallLog.Calls.DATE// 通话记录的日期
//                                    , CallLog.Calls.DURATION// 通话时长
//                                    , CallLog.Calls.TYPE}// 通话类型
//                            , where, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
                    //        // 3.通过Cursor获得数据
            );
            if (null == cursor) {
                return list;
            }
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                String date = DateUtil.millis2String(dateLong);
                int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
//                String typeString = "";
//                switch (type) {
//                    case CallLog.Calls.INCOMING_TYPE:
//                        typeString = "打入电话";
//                        break;
//                    case CallLog.Calls.OUTGOING_TYPE:
//                        typeString = "打出电话";
//                        break;
//                    case CallLog.Calls.MISSED_TYPE:
//                        typeString = "未接电话";
//                        break;
//                    default:
//                        break;
//                }
                PhoneRecordBean recordBean = new PhoneRecordBean();
                recordBean.setContacts((name == null) ? "未备注联系人" : name);
                recordBean.setContactsPhone(number);
                recordBean.setContactTime(date);
                recordBean.setCallDuration((duration / 60) + "分钟");
                recordBean.setCallType(String.valueOf(type));
                list.add(recordBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert cursor != null;
            cursor.close();
        }
        return list;
    }

    /**
     * 根据经纬度获取地理位置
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return {@link Address}
     */
    public static Address getAddress(Context context, double latitude, double longitude) {
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0)
                return addresses.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ArrayList<String> getAppInfoList(Context applicationContext) {
        ArrayList<String> appList = new ArrayList<>();
        //包管理器
        PackageManager pm = applicationContext.getPackageManager();
        //在子线程中获取手机安装的应用程序信息
        //获取手机中所有安装的应用集合
        List<ApplicationInfo> applicationInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        //遍历所有的应用集合
        for (ApplicationInfo info : applicationInfos) {
            Log.i("tag_applicationInfo", info.toString());
            //获取应用程序的图标
            //获取应用的名称
            String app_name = info.loadLabel(pm).toString();
            //获取应用的包名
            String packageName = info.packageName;
            try {
                //获取应用的版本号
                PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
                String app_version = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            //判断应用程序是否是用户程序
            if (filterApp(info)) {
                appList.add(app_name);
            }
        }
        return appList;
    }


    //判断应用程序是否是用户程序
    public static boolean filterApp(ApplicationInfo info) {
        //原来是系统应用，用户手动升级
        if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
            return true;
            //用户自己安装的应用程序
        } else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
            return true;
        }
        return false;
    }


    /**
     * 根据经纬度获取所在街道
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return 所在街道
     */
    public static String getStreet(Context context, double latitude, double longitude) {
        Address address = getAddress(context, latitude, longitude);
        return address == null ? "unknown" : address.getAddressLine(0) + "," + address.getAddressLine(1) + "," + address.getAddressLine(2);
    }


}
